<template>
    <div class="header">
      <el-row type="flex" justify="space-between" align="middle" class="header-row">
        <!-- 中间的搜索框 -->
        <el-col :span="12" class="search-container">
          <el-input
            placeholder="请输入搜索内容"
            v-model="searchText"
            class="search-input"
            prefix-icon="el-icon-search"
          />
          <el-button  icon="el-icon-search">搜索</el-button>
        </el-col>
  
        <!-- 右上角的登录头像和退出按钮 -->
        <el-col :span="8" class="user-actions">
          <el-avatar
            shape="circle"
            size="40"
            :src="this.$store.state.user.loginStatus?'https://vue.ruoyi.vip/static/img/profile.473f5971.jpg':'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'"
            class="avatar"
          />
          <el-dropdown v-if="this.$store.state.user.loginStatus">
            <span class="el-dropdown-link" >
              {{this.$store.state.user.userName}}<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item><el-button type="text" class="logout-btn" @click="openDialogFormVisible" >个人中心</el-button></el-dropdown-item>
              <el-dropdown-item><el-button type="text" class="logout-btn" @click="openDialogFormVisible2" >开播设置</el-button></el-dropdown-item>
              <el-dropdown-item divided><el-button type="text" class="logout-btn" @click="logout" >退出</el-button></el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-button type="text" class="ut-btn" @click="showDialog = true" v-if="!this.$store.state.user.loginStatus">登录</el-button>
          </el-col>
      </el-row>

    <!-- 登录弹框 -->
    <el-dialog
      title="登录"
      :visible.sync="showDialog"
      width="30%"
      :close-on-click-modal="false">
      <!-- 二维码 -->
      <div class="qr-code-container">
        <img
          src="@/assets/qrcode.png"
          alt="登录二维码"
          class="qr-code"/>
      </div>
      <!-- 说明文字 -->
      <div class="login-instructions">
        <p style="font-size: 16px;">1. 请使用微信扫描上方二维码<span style="color: red; ">关注公众号</span></p>
        <p style="font-size: 16px;">2. 回复文字“<span style="color: red; ">验证码</span>”获取，输入验证码后即可登录</p>
      </div>
      <!-- 数字输入框和登录按钮 -->
      <div class="input-button-container" @keydown.enter="handleLogin">
        <el-input
          v-model="loginCode"
          placeholder="请输入验证码"
          maxlength="6"
          clearable
          class="number-input"
        />
        <el-button type="primary" @click="handleLogin" class="login-button">
          登录
        </el-button>
      </div>
    </el-dialog>

    
    <!-- 个人资料 -->
    <el-dialog title="个人资料" :visible.sync="dialogFormVisible"
      width="30%"
      :close-on-click-modal="false">
      <el-form ref="form"  label-width="80px">
        <el-form-item label="用户名称">
          <el-input v-model="userName"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSave">确 定</el-button>
      </div>
    </el-dialog>


    <!-- 开播设置 -->
    <el-dialog title="开播设置" :visible.sync="dialogFormVisible2"
      width="30%"
      :close-on-click-modal="false">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm"  label-width="100px">
        <el-form-item label="直播标题" prop="title">
          <el-input v-model="ruleForm.title" style="width: 80%;" placeholder="请输入直播标题"></el-input>
        </el-form-item>
        <el-form-item label="直播分类" prop="typeId">
          <el-select v-model="ruleForm.typeId" placeholder="请选择直播分类" style="width: 80%;">
            <el-option
              v-for="item in typeList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="直播封面">
          <el-radio-group v-model="form.resource">
            <el-radio label="自动设置"></el-radio>
            <el-radio label="手动设置"></el-radio>
          </el-radio-group>
        </el-form-item> -->
        <el-form-item label="你的rtmp地址">
          <el-input v-model="ruleForm.rtmpUrl" style="width: 80%;" :disabled="true"></el-input><el-button @click.prevent="copyToClipboard(ruleForm.rtmpUrl)">复制</el-button>
        </el-form-item>
        <el-form-item label="你的推流码">
          <el-input v-model="ruleForm.rtmpCode" style="width: 80%;" :disabled="true"></el-input><el-button @click.prevent="copyToClipboard(ruleForm.rtmpCode)">复制</el-button>
        </el-form-item>
        <p style="color: #5e6d82">每次重新开播，请复制新的rtmp地址和推流码到<a href="https://apps.belacad.cn/app/5/obs-studio?bd_vid=11836407214920436299" target="_blank">OBS</a>的服务器里</p>
      </el-form>
      <div style="text-align: center; margin:0 20px;">
        <el-button type="success" @click="submitForm('ruleForm')" v-if="this.bOpenPlayButton" class="login-button">
          开始直播
        </el-button>
        <el-button type="danger" @click="closeForm" v-if="!this.bOpenPlayButton"  class="login-button">
          关闭直播
        </el-button>
      </div>
    </el-dialog>

    </div>
  </template>
  
  <script>
import { getToken } from '@/utils/auth'
import { getUserUniqueId } from '@/utils/uniqueId';
import { updateUserName,getTypeList } from '@/api/common'
import { openPlay,getRoomUserInfo,closePlay } from '@/api/room'
  export default {
    data() {
      return {
        showDialog: false, // 验证码控制弹框显示
        loginCode: "", // 数字输入框的值
        searchText: '', // 搜索框绑定值
        dialogFormVisible: false,//个人资料控制弹框显示
        dialogFormVisible2: false,//开播设置控制弹框显示
        bOpenPlayButton: true,//是否显示开播按钮
        userName:"",
        typeList: [], //分类列表
        ruleForm:{ 
            title: '',
            typeId: '',
            rtmpUrl: '',
            rtmpCode: ''
        },
        rules: {
          title: [
            { required: true, message: '请输入直播标题', trigger: 'blur' }
          ],
          typeId: [
            { required: true, message: '请选择直播分类', trigger: 'blur' }
          ],
        }
      };
    },
    created() {
      this.getLoginInfo();
      this.getTypeList();
      this.userName=this.$store.state.user.userName;
    },
    methods: {
      //查询个人资料方法
      getLoginInfo(){
        if(getToken()){
          this.$store.dispatch("GetInfo",getUserUniqueId()).then(() => {});
        }
      },
      //查询分类下拉
      getTypeList(){
        getTypeList().then(res => {
          this.typeList=res.data;
        }).catch(error => {
        })
      },
      //退出登录方法
      logout() {
        this.$confirm('确认要退出登录?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
            this.$store.dispatch("LogOut").then(response => {
              this.$message.success(response.msg);
            }).catch(() => {
            });
        }).catch(() => {     
        });
      },
      //登录方法
      handleLogin(done) {
        if (!this.loginCode) {
          this.$message.error("请输入有效的数字登录码！");
          return;
        }
        this.$store.dispatch("Login", this.loginCode).then(response => {
              this.getLoginInfo();//拉取登录信息
              this.$message.success("登录成功");//弹框提示信息
              this.showDialog = false; // 登录后关闭弹框
              this.loginCode = "";
              done();
          }).catch(() => {
          });
      },
      //打开个人中心窗口
      openDialogFormVisible(){
        this.userName=this.$store.state.user.userName;
        this.dialogFormVisible=true;
      },
      //打开开播窗口
      openDialogFormVisible2(){
        getRoomUserInfo().then(res => {
          this.ruleForm=res.data;
          if(res.data!=null && res.data.state==true){
              this.bOpenPlayButton=false;
          }
        }).catch(error => {
          this.$message.error("失败");//弹框提示信息
        })
        this.dialogFormVisible2=true;
      },
      //开播
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
              openPlay(this.ruleForm).then(res => {
                this.ruleForm=res.data;
                if(res.data!=null && res.data.state==true){
                    this.bOpenPlayButton=false;
                }
                this.$message.success("开播成功"); 
              }).catch(error => {
              })
          }
        });
      },
      closeForm(){

        this.$confirm('确认要关闭直播?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
            closePlay().then(res => {
              this.bOpenPlayButton=true;
              this.ruleForm={ 
                  title: '',
                  typeId: '',
                  rtmpUrl: '',
                  rtmpCode: ''
              },
              this.$message.success("关播成功"); 
          }).catch(error => {
          })
        }).catch(() => {     
        });

        
      },
      //复制
      copyToClipboard(text) {
        if (!text) {
          this.$message.error('复制内容为空！');
          return;
        }
        navigator.clipboard.writeText(text).then(() => {
          this.$message.success('复制成功！');
        }).catch((err) => {
          console.error('复制失败:', err);
          this.$message.error('复制失败，请重试！');
        });
      },
      //修改资料保存方法
      handleSave() {
          updateUserName(this.userName).then(res => {
            this.$message.success("修改成功"); 
            this.dialogFormVisible=false;
            setTimeout(() => {
              // 这里是你想要延迟两秒执行的代码
              window.location.reload();
            }, 1500);
          }).catch(error => {
          })
      },
    },
  };
  </script>
  
  <style scoped>
  .header {
    padding: 0px 20px;
    /* border-bottom: 1px solid #ddd; */
  }
  .header-row {
    margin-left: 500px;
    height: 50px;
  }
  .search-container {
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .search-input {
    width: 80%;
  }
  .user-actions {
    display: flex;
    justify-content: flex-end;
    align-items: center;
  }
  .avatar {
    margin-right: 10px;
    cursor: pointer;
  }
  .logout-btn {
    color: #409eff;
  }
  .qr-code-container {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.qr-code {
  width: 200px;
  height: 200px;
  border: 1px solid #ddd;
  border-radius: 8px;
}

.login-instructions {
  text-align: center;
  color: #666;
}
.input-button-container {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 10px; /* 设置输入框和按钮之间的间距 */
  margin-bottom: 20px;
}

.number-input {
  width: 150px; /* 设置输入框的固定宽度 */
}


.login-button {
  flex-shrink: 0; /* 按钮保持固定大小 */
}
.dialog-footer {
  text-align: right;
}

.demo-drawer__content {
    display: flex;
    flex-direction: column;
    height: 100%
}

.demo-drawer__content form {
    flex: 1;
}

.demo-drawer__footer {
    display: flex;
}

.demo-drawer__footer button {
    flex: 1
}
.el-dropdown-link {
    cursor: pointer;
    color: #409EFF;
  }
  .el-icon-arrow-down {
    font-size: 12px;
  }
  </style>
  